/**
 * 
 */
package cn.panda.edu.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 类描述： 文件相关操作
 * 
 */
public class FileUtil {
	/**
	 * 
	 * @Title: uploadFile
	 * @Description: 单文件上传工具
	 * @param file  // 上传的文件对象
	 * @return void
	 */
	public static String uploadFile(MultipartFile file) throws Exception {
		String uploadFolder = "d://uploadFiles/";//本地
//		String uploadFolder = "/uploadFiles/"; //线上
//		String accessPath="/file/**";
		String newUploadFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString() + new Random().nextInt(10);
		String uploadFileName = file.getOriginalFilename();

		String uploadFileSuffix = uploadFileName.substring(uploadFileName.indexOf('.') + 1, uploadFileName.length());

		String fileName = newUploadFileName + "." + uploadFileSuffix;
//		String originalFilename = file.getOriginalFilename();
//		String fileName = FileUtil.getFileName(FileUtil.getFileEx(originalFilename));
		File tagetFile = new File(uploadFolder + fileName);// 创建文件对象
		File dir = tagetFile.getParentFile();
		if (!dir.exists()) {
			dir.mkdirs(); // 先创建目录
		}
		file.transferTo(tagetFile);
		String filePath = uploadFolder + fileName;

		return filePath;
//		String newUploadFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString()
//				+ new Random().nextInt(10);
//		String uploadFileName = file.getOriginalFilename();
//		// 截取上传文件的后缀
//		String uploadFileSuffix = uploadFileName.substring(uploadFileName.indexOf('.') + 1, uploadFileName.length());
//		FileOutputStream fos = null;
//		FileInputStream fis = null;
//		// 设置本地储存文件路径
//		File saveFile = new File(Constant.SAVE_PATH);
//		String savePath = saveFile + "//" + newUploadFileName + "." + uploadFileSuffix;
//		if (saveFile.exists()) {
//			try {
//				fis = (FileInputStream) file.getInputStream();
//				fos = new FileOutputStream(new File(savePath));
//				byte[] temp = new byte[1024];
//				int i = fis.read(temp);
//				while (i != -1) {
//					fos.write(temp, 0, temp.length);
//					fos.flush();
//					i = fis.read(temp);
//				}
//			} catch (IOException e) {
//				e.printStackTrace();
//			} finally {
//				if (fis != null) {
//					try {
//						fis.close();
//					} catch (IOException e) {
//						e.printStackTrace();
//					}
//				}
//				if (fos != null) {
//					try {
//						fos.close();
//					} catch (IOException e) {
//						e.printStackTrace();
//					}
//				}
//			}
//		}
//		return "d:"+File.separator + "uploadfiles" + File.separator + newUploadFileName + "." + uploadFileSuffix;
	}


	public static String getFileExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}
	/**
	 * 
	* @Title: downloadFile 
	* @Description: 下载文件
	* void
	 */
	public static void downloadFile(String url, HttpServletResponse response) throws Exception{
		String uploadFolder = "d://uploadFiles/";//本地
//		String uploadFolder = "/uploadFiles/"; //线上
		String pre = uploadFolder;
		String fileName = url.substring(url.indexOf(pre) + pre.length());
		Path file = Paths.get(uploadFolder, fileName);
		if (Files.exists(file)) {
			String exName = getFileExtensionName(url);
			// String filename = file.getFileName().toString();
			response.setContentType("application/" + exName);
			response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
			Files.copy(file, response.getOutputStream());
		} else {
			throw new RuntimeException("The file is not exist");
		}

//		res.setHeader("content-type", "application/octet-stream");
//		res.setContentType("application/octet-stream");
//		res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
//		byte[] buff = new byte[1024];
//		BufferedInputStream bis = null;
//		OutputStream os = null;
//		try {
//			os = res.getOutputStream();
//			bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
//			int i = bis.read(buff);
//			while (i != -1) {
//				os.write(buff, 0, buff.length);
//				os.flush();
//				i = bis.read(buff);
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			if (bis != null) {
//				try {
//					bis.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
	}
	
	/**
	 * 
	* @Title: uploadFiles 
	* @Description: 多文件上传
	* @param files  //多文件对象
	* @return  List<String>  //返回要存储的路径集合，分别存入即可
	* 
	 */
	public static List<String> uploadFiles(MultipartFile[] files) {
			MultipartFile file = null ;
			List<String> savePaths = new ArrayList<String>() ;
		    for (int i = 0; i < files.length; ++i) {
		    	file = files[i] ;
		    	String uploadFileName = file.getOriginalFilename();
		    	String newUploadFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString()
						+ new Random().nextInt(10);

				// 截取上传文件的后缀
				String uploadFileSuffix = uploadFileName.substring(uploadFileName.indexOf('.') + 1, uploadFileName.length());
				FileOutputStream fos = null;
				FileInputStream fis = null;
				// 设置本地储存文件路径
				File saveFile = new File(Constant.SAVE_PATH);
				String savePath = saveFile + "//" + newUploadFileName + "." + uploadFileSuffix;
				if (saveFile.exists()) {
					try {
						fis = (FileInputStream) file.getInputStream();
						fos = new FileOutputStream(new File(savePath));
						byte[] temp = new byte[1024];
						int tem = fis.read(temp);
						while (tem != -1) {
							fos.write(temp, 0, temp.length);
							fos.flush();
							i = fis.read(temp);
						}
						savePaths.add(savePath) ;
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						if (fis != null) {
							try {
								fis.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
						if (fos != null) {
							try {
								fos.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}
		    }
		    return savePaths ;
	}
}





